const express = require('express');
const router = express.Router();
const { pool } = require('../database');

// 获取所有医生列表
router.get('/', async (req, res) => {
  try {
    const { hospital_id, department_id, work_time_type, is_available } = req.query;
    
    let sql = `
      SELECT d.id, d.hospital_id, d.department_id, d.name, d.short_name, d.photo, d.title,
             d.specialties, d.introduction, d.detailed_intro, d.schedule_days,
             d.work_time_type, d.quota_numbers, d.registration_fee, d.weight,
             d.is_available, d.created_at, d.updated_at,
             h.name as hospital_name, dep.name as department_name
      FROM doctors d
      LEFT JOIN hospitals h ON d.hospital_id = h.id
      LEFT JOIN departments dep ON d.department_id = dep.id
      WHERE 1=1
    `;
    
    const params = [];
    
    if (hospital_id) {
      sql += ' AND d.hospital_id = ?';
      params.push(hospital_id);
    }
    
    if (department_id) {
      sql += ' AND d.department_id = ?';
      params.push(department_id);
    }
    
    if (work_time_type) {
      sql += ' AND d.work_time_type = ?';
      params.push(work_time_type);
    }
    
    if (is_available !== undefined) {
      sql += ' AND d.is_available = ?';
      params.push(is_available === 'true');
    }
    
    sql += ' ORDER BY d.weight DESC, d.created_at DESC';
    
    const [rows] = await pool.execute(sql, params);
    
    res.json({
      success: true,
      data: rows,
      message: '获取医生列表成功'
    });
  } catch (error) {
    console.error('获取医生列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取医生列表失败',
      error: error.message
    });
  }
});

// 根据ID获取医生详情
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const [rows] = await pool.execute(`
      SELECT d.id, d.hospital_id, d.department_id, d.name, d.short_name, d.photo, d.title,
             d.specialties, d.introduction, d.detailed_intro, d.schedule_days,
             d.work_time_type, d.quota_numbers, d.registration_fee, d.weight,
             d.is_available, d.created_at, d.updated_at,
             h.name as hospital_name, dep.name as department_name
      FROM doctors d
      LEFT JOIN hospitals h ON d.hospital_id = h.id
      LEFT JOIN departments dep ON d.department_id = dep.id
      WHERE d.id = ?
    `, [id]);
    
    if (rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '医生不存在'
      });
    }
    
    res.json({
      success: true,
      data: rows[0],
      message: '获取医生详情成功'
    });
  } catch (error) {
    console.error('获取医生详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取医生详情失败',
      error: error.message
    });
  }
});

// 创建新医生
router.post('/', async (req, res) => {
  try {
    const {
      hospital_id, department_id, name, short_name, photo, title, specialties,
      introduction, detailed_intro, schedule_days, work_time_type,
      quota_numbers, registration_fee, weight, is_available
    } = req.body;
    
    // 验证必填字段
    if (!hospital_id || !department_id || !name || !short_name) {
      return res.status(400).json({
        success: false,
        message: '医院ID、科室ID、医生姓名和内部简称为必填项'
      });
    }
    
    // 验证医院是否存在
    const [hospital] = await pool.execute('SELECT id FROM hospitals WHERE id = ?', [hospital_id]);
    if (hospital.length === 0) {
      return res.status(400).json({
        success: false,
        message: '指定的医院不存在'
      });
    }
    
    // 验证科室是否存在
    const [department] = await pool.execute('SELECT id FROM departments WHERE id = ?', [department_id]);
    if (department.length === 0) {
      return res.status(400).json({
        success: false,
        message: '指定的科室不存在'
      });
    }
    
    // 验证工作时间类型
    if (work_time_type && ![1, 2, 3].includes(work_time_type)) {
      return res.status(400).json({
        success: false,
        message: '工作时间类型必须为1(上午)、2(下午)或3(全天)'
      });
    }
    
    const [result] = await pool.execute(`
      INSERT INTO doctors (hospital_id, department_id, name, short_name, photo, title, specialties,
                          introduction, detailed_intro, schedule_days, work_time_type,
                          quota_numbers, registration_fee, weight, is_available)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `, [
      hospital_id, department_id, name, short_name, photo || null, title || null, specialties || null,
      introduction || null, detailed_intro || null, schedule_days || '1,2,3,4,5', 
      work_time_type || 3, quota_numbers || 0, registration_fee || 0, 
      weight || 0, is_available !== false
    ]);
    
    res.status(201).json({
      success: true,
      data: { id: result.insertId },
      message: '创建医生成功'
    });
  } catch (error) {
    console.error('创建医生失败:', error);
    res.status(500).json({
      success: false,
      message: '创建医生失败',
      error: error.message
    });
  }
});

// 更新医生信息
router.put('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const {
      hospital_id, department_id, name, photo, title, specialties,
      introduction, detailed_intro, schedule_days, work_time_type,
      quota_numbers, registration_fee, weight, is_available
    } = req.body;
    
    // 检查医生是否存在
    const [existing] = await pool.execute('SELECT id FROM doctors WHERE id = ?', [id]);
    if (existing.length === 0) {
      return res.status(404).json({
        success: false,
        message: '医生不存在'
      });
    }
    
    // 如果更新了医院ID，验证新医院是否存在
    if (hospital_id) {
      const [hospital] = await pool.execute('SELECT id FROM hospitals WHERE id = ?', [hospital_id]);
      if (hospital.length === 0) {
        return res.status(400).json({
          success: false,
          message: '指定的医院不存在'
        });
      }
    }
    
    // 如果更新了科室ID，验证新科室是否存在
    if (department_id) {
      const [department] = await pool.execute('SELECT id FROM departments WHERE id = ?', [department_id]);
      if (department.length === 0) {
        return res.status(400).json({
          success: false,
          message: '指定的科室不存在'
        });
      }
    }
    
    // 验证工作时间类型
    if (work_time_type && ![1, 2, 3].includes(work_time_type)) {
      return res.status(400).json({
        success: false,
        message: '工作时间类型必须为1(上午)、2(下午)或3(全天)'
      });
    }
    
    await pool.execute(`
      UPDATE doctors SET
        hospital_id = ?, department_id = ?, name = ?, photo = ?, title = ?, 
        specialties = ?, introduction = ?, detailed_intro = ?, schedule_days = ?,
        work_time_type = ?, quota_numbers = ?, registration_fee = ?, 
        weight = ?, is_available = ?, updated_at = CURRENT_TIMESTAMP
      WHERE id = ?
    `, [
      hospital_id, department_id, name, photo, title, specialties,
      introduction, detailed_intro, schedule_days, work_time_type,
      quota_numbers, registration_fee, weight, is_available, id
    ]);
    
    res.json({
      success: true,
      message: '更新医生信息成功'
    });
  } catch (error) {
    console.error('更新医生信息失败:', error);
    res.status(500).json({
      success: false,
      message: '更新医生信息失败',
      error: error.message
    });
  }
});

// 删除医生
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    // 检查医生是否存在
    const [existing] = await pool.execute('SELECT id FROM doctors WHERE id = ?', [id]);
    if (existing.length === 0) {
      return res.status(404).json({
        success: false,
        message: '医生不存在'
      });
    }
    
    // 删除医生（会级联删除相关数据）
    await pool.execute('DELETE FROM doctors WHERE id = ?', [id]);
    
    res.json({
      success: true,
      message: '删除医生成功'
    });
  } catch (error) {
    console.error('删除医生失败:', error);
    res.status(500).json({
      success: false,
      message: '删除医生失败',
      error: error.message
    });
  }
});

// 更新医生状态
router.patch('/:id/status', async (req, res) => {
  try {
    const { id } = req.params;
    const { is_available } = req.body;
    
    if (typeof is_available !== 'boolean') {
      return res.status(400).json({
        success: false,
        message: 'is_available 必须为布尔值'
      });
    }
    
    await pool.execute(
      'UPDATE doctors SET is_available = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [is_available, id]
    );
    
    res.json({
      success: true,
      message: `医生已${is_available ? '启用' : '禁用'}`
    });
  } catch (error) {
    console.error('更新医生状态失败:', error);
    res.status(500).json({
      success: false,
      message: '更新医生状态失败',
      error: error.message
    });
  }
});

// 更新医生权重
router.patch('/:id/weight', async (req, res) => {
  try {
    const { id } = req.params;
    const { weight } = req.body;
    
    if (typeof weight !== 'number') {
      return res.status(400).json({
        success: false,
        message: 'weight 必须为数字'
      });
    }
    
    await pool.execute(
      'UPDATE doctors SET weight = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [weight, id]
    );
    
    res.json({
      success: true,
      message: '更新医生权重成功'
    });
  } catch (error) {
    console.error('更新医生权重失败:', error);
    res.status(500).json({
      success: false,
      message: '更新医生权重失败',
      error: error.message
    });
  }
});

// 获取医生可用时间段
router.get('/:id/available-slots', async (req, res) => {
  try {
    const { id } = req.params;
    const { date } = req.query;
    
    if (!date) {
      return res.status(400).json({
        success: false,
        message: '请提供日期参数'
      });
    }
    
    // 调用存储过程
    const [rows] = await pool.execute('CALL GetDoctorAvailableSlots(?, ?)', [id, date]);
    
    res.json({
      success: true,
      data: rows[0],
      message: '获取医生可用时间段成功'
    });
  } catch (error) {
    console.error('获取医生可用时间段失败:', error);
    res.status(500).json({
      success: false,
      message: '获取医生可用时间段失败',
      error: error.message
    });
  }
});

module.exports = router;
